// pages/personal/order.js
Page({

    /**
     * 页面的初始数据
     */
    data: {
        tabs: [
            { label: "全部订单", state: '' },
            { label: "待付款", state: 0 },
            { label: "已付款", state: 1 },
        ],
        current: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {
        this.loadData()
    },
    clickTab(evt) {
        this.setData({
            current: evt.currentTarget.dataset.current
        })
        this.loadData()
    },
    loadData() {
        const { current, tabs } = this.data
        let { page = 1, total = 2, list = [], loading = false } = tabs[current]
        if (page > total || loading) {
            return
        }
        wx.showLoading({
            title: '加载中...',
        })
        this.setData({
            [`tabs[${current}].loading`]: true
        })
        getApp().http.get("member/my-orders", {
            data: {
                "SupplierOrderSearch[pay_state]": tabs[current].state
            }
        }).then(res => {
            page++
            total = res.data.total
            list.push(...res.data.item)
            loading = false
            this.setData({
                [`tabs[${current}]`]: Object.assign(tabs[current], { page, total, list, loading })
            })
            wx.hideLoading()
            wx.stopPullDownRefresh()
        })
    },
    payAgain(evt) {
        const { id, index } = evt.currentTarget.dataset
        console.log(id, index)
        wx.showLoading({
            title: '加载中...',
        })
        getApp().http.get("order/pay", {
            data: { id, sid: this.data.tabs[this.data.current].list[index].supplier_id },
        }).then(res => {
            wx.hideLoading()
            const js = res.data
            wx.requestPayment({
                'timeStamp': js.timeStamp,
                'nonceStr': js.nonceStr,
                'package': js.package,
                'signType': js.signType,
                'paySign': js.paySign,
                'success': function (res) {
                    wx.showToast({
                        title: '支付成功！',
                    })
                },
                'fail': function (res) {
                    app.wxToast.warn("支付失败，请重新支付")
                }
            })
        }).catch(err => {
            getApp().wxToast.warn(err.message)
        })
    },
    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {
        const { current, tabs } = this.data
        this.setData({
            [`tabs[${current}]`]: Object.assign(tabs[current], { page: 1, total: 2, list: [] })
        })
        this.loadData()
    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {
        this.loadData()
    },

})